package filters;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;

/**
 * Workaround for closing connections acquired in *header.jsp. Connections registered 
 * in the request object (via setAttribute()) are picked up by doFilter() and closed
 * if necessary. The request attribute name is specified as filter parameter "key".
 * 
 * @author KENNETHLCH
 * @version $Id: ConnectionCleanupFilter.java,v 1.1.1.1 2013/08/16 05:35:48 tengyang Exp $
 */
public class ConnectionCleanupFilter implements Filter {
    
    private Logger logger = Logger.getLogger(getClass());
    
    private String key;

    @Override
    public void destroy() {
       
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        
        try {
            chain.doFilter(req, resp);
        } finally {
            try {
                Connection con = (Connection) req.getAttribute(key);

                if (con != null && !con.isClosed()) {
                    con.close();
                }
            } catch (SQLException e) {
                logger.warn("Connection cleanup failed", e);
            }
        }
    }

    @Override
    public void init(FilterConfig config) throws ServletException {
        key = config.getInitParameter("key");
        if (key == null)
            key = "jis.con";
    }

}
